<?php

/**
 * Subclass for performing query and update operations on the 'statement' table.
 *
 *
 *
 * @package lib.model
 */
class LypoStatementPeer extends BaseLypoStatementPeer
{

	static $collPerfectOppositesReactions = null;

	public static function populateObjectsWithRespects(ResultSet $rs)
	{
		$results = array();

		$cls = LypoStatementPeer::getOMClass();
		$cls = sfPropel::import($cls);
		while($rs->next()) {

			$obj = new $cls();
			$offset = $obj->hydrate($rs);
			$obj->setRespects($rs->getInt($offset));

			$results[] = $obj;

		}
		return $results;
	}

	public static function populateObjectsWithDates(ResultSet $rs)
	{
		$results = array();

		$cls = LypoStatementPeer::getOMClass();
		$cls = sfPropel::import($cls);
		while($rs->next()) {

			$obj = new $cls();
			$offset = $obj->hydrate($rs);
			$obj->setDateUsed($rs->getDate($offset,'U'));

			$results[] = $obj;

		}
		return $results;
	}

	static public function updateReactionCount($statement_id){
		$c = new Criteria();
		$c->add(ReactionPeer::STATEMENT_ID,$statement_id);
		$num_reactions = ReactionPeer::doCount($c);
		if($num_reactions > 0){
			$c = new Criteria();
			$c->add(LypoStatementPeer::ID,$statement_id);
			$c->add(LypoStatementPeer::REACTION_COUNT,$num_reactions);
			LypoStatementPeer::doUpdate($c);
		}
	}

	static public function getAllStatements(){
		$c = new Criteria();
		return self::doSelect($c);
	}

	static public function getRegistrationStatements(){
		$c = self::getRegistrationStatementsCriteria();
		return self::doSelect($c);
	}

	static public function getTodaysDebate(){
		//Kijken of er een statement voor vandaag beschikbaar is
		$today = date('Y-m-d');
		$c = new Criteria();
		$c->add(StatementDayPeer::DATUM,$today);
		$statements = StatementDayPeer::doSelectJoinLypoStatement($c);
		if($statements){
			//JA? Statement teruggeven
			return $statements[0]->getLypoStatement();
		}else{
			//NEE? Dan huidige datum + random statement inserten
			//Eerste alle reeds gebruikte statements ophalen
			$all = StatementDayPeer::doSelect(new Criteria());
			$used_statement_ids = array();
			if($all){
				foreach($all as $daystatement):
				$used_statement_ids[$daystatement->getStatementId()]=1;
				endforeach;
			}
			//Random eentje selecteren (met uitzondering van al gebruikte)
			$c = new Criteria();
			if(count($used_statement_ids)){
				$c->add(LypoStatementPeer::ID,array_keys($used_statement_ids),Criteria::NOT_IN);
			}
			$c->addAscendingOrderByColumn('RAND()');
			$c->setLimit(1);
			$today_statement = LypoStatementPeer::doSelectOne($c);
			if($today_statement){
				$sd = new StatementDay();
				$sd->setDatum($today);
				$sd->setLypoStatement($today_statement);
				$sd->save();
				return $today_statement;
			}
			return false;
		}
	}


	public static function doSelectWithDates(Criteria $criteria, $con = null)
	{
		$rs = self::doSelectRS($criteria,$con);
		return self::populateObjectsWithDates($rs);
	}
	
	
	public static function doSelectWithRespects(Criteria $criteria, $con = null)
	{
		$rs = self::doSelectRS($criteria,$con);
		return self::populateObjectsWithRespects($rs);
	}	

	static public function getDebatesByNamePager($page=1){
		//Debatten op naam
		$c = new Criteria();
		$c->addAscendingOrderByColumn(LypoStatementPeer::TEXT);
		$pager = new sfPropelPager('LypoStatement',10);
		$pager->setCriteria($c);
		$pager->setPage($page);
		$pager->init();
		return $pager;
	}


	static public function getRecentDebatesPager($page=1){
		//Kijken of er een statement voor vandaag beschikbaar is
		$c = new Criteria();
		$c->add(StatementDayPeer::DATUM,time(),Criteria::LESS_THAN);
		$c->addAsColumn('datum',StatementDayPeer::DATUM);
		$c->addJoin(LypoStatementPeer::ID,StatementDayPeer::STATEMENT_ID);
		$c->addDescendingOrderByColumn(StatementDayPeer::DATUM);

		$pager = new sfPropelPager('LypoStatement',10);
		$pager->setCriteria($c);
		$pager->setPeerMethod('doSelectWithDates');
		$pager->setPage($page);
		$pager->init();
		return $pager;
	}

	static public function getUserDebatesReactionsPager($user,$page=1,$max_per_page=5){
		//Eerst alle statement ids ophalen waarop een reactie is gegeven door deze gebruikers
		$con = Propel::getConnection();
		$sql = sprintf('SELECT DISTINCT(%s) as statement_id FROM %s WHERE %s=%s',ReactionPeer::STATEMENT_ID,ReactionPeer::TABLE_NAME,ReactionPeer::USER_ID,$user->getId());
		$stmt = $con->prepareStatement($sql);
		$rs = $stmt->executeQuery();

		if($rs->getRecordCount()==0) return false;
		if($rs->getRecordCount()>0){
			$statement_ids = array();
			while($rs->next()){
				$statement_ids[]=$rs->getInt('statement_id');
			}
		}

		//Dan Alle statements ophalen en joinen met answers ....

		if(count($statement_ids)){
			$c = new Criteria();
			$c->add(ReactionPeer::STATEMENT_ID,$statement_ids,Criteria::IN);
			$c->add(ReactionPeer::USER_ID,$user->getId());
			$c->addAscendingOrderByColumn(LypoStatementPeer::SORTORDER);
			$pager = new sfPropelPager('Reaction',$max_per_page);
			$pager->setCriteria($c);
			$pager->setPeerMethod('doSelectJoinLypoStatement');
			$pager->setPage($page);
			$pager->init();
			return $pager;
		}



	}

	static public function getRespectedDebatesPager($page=1){
		$c = new Criteria();
		$c->addAsColumn('total',"SUM(".ReactionPeer::NUM_RESPECTS.")",Criteria::CUSTOM);
		$c->addJoin(LypoStatementPeer::ID,ReactionPeer::STATEMENT_ID);
		$c->addDescendingOrderByColumn('total');
		$c->addGroupByColumn(ReactionPeer::STATEMENT_ID);

		$pager = new sfPropelPager('LypoStatement',10);
		$pager->setCriteria($c);
		$pager->setPeerMethod('doSelectWithRespects');
		$pager->setPage($page);
		$pager->init();		
		
		return $pager;
	}	
	

	static public function getRespectedDebates($limit=10){
		$c = new Criteria();
		$c->addAsColumn('total',"SUM(".ReactionPeer::NUM_RESPECTS.")",Criteria::CUSTOM);
		$c->addJoin(LypoStatementPeer::ID,ReactionPeer::STATEMENT_ID);
		$c->addDescendingOrderByColumn('total');
		$c->addGroupByColumn(ReactionPeer::STATEMENT_ID);
		$c->setLimit(10);
		$ret = self::populateObjectsWithRespects(LypoStatementPeer::doSelectRS($c));
		return $ret;
	}

	static public function getRegistrationStatementsCriteria(){
		$c = new Criteria();
		$c->add(LypoStatementPeer::FOR_REGISTRATION,true);
		$c->addAscendingOrderByColumn(LypoStatementPeer::SORTORDER);
		return $c;
	}


	static public function getPerfectOppositesReactionCounts(User $user){
		if(!self::$collPerfectOppositesReactions){
			$ret = array();
			$opposites = $user->getPerfectOppositesIds(10);
			//Eerst alle perfect_opposites ophalen voor
			if(count($opposites['ids'])){
				$opposite_ids = join(',',$opposites['ids']);
				$conn = Propel::getConnection();
				$sql = sprintf('SELECT statement_id, count(*) as total FROM reaction WHERE user_id in (%s) GROUP BY statement_id',$opposite_ids);
				$stmt = $conn->prepareStatement($sql);
				$rs = $stmt->executeQuery();
				if($rs){
					while($rs->next()){
						$ret[$rs->getInt('statement_id')]=$rs->getInt('total');
					}
				}
			}
			self::$collPerfectOppositesReactions = $ret;
			return self::$collPerfectOppositesReactions;
		}else{
			return self::$collPerfectOppositesReactions;
		}

	}

	static public function getPerfectOppositesReactionCount(User $user, $statement_id){
		$reaction_counts = self::getPerfectOppositesReactionCounts($user);
		if(count($reaction_counts)){
			if(isset($reaction_counts[$statement_id])) return $reaction_counts[$statement_id];
		}
		return 0;
	}




}
